<template>
  <div class="chat-container">
    <div class="chat-header">
      <div class="back-button" @click="goBack">
        <el-icon><ArrowLeft /></el-icon> 返回
      </div>
      <div class="chat-title">
        <el-avatar 
          v-if="chatPartner" 
          :src="chatPartner.avatar" 
          :size="32" 
          class="title-avatar"
        >
          {{ chatPartner.nickname?.charAt(0) || chatPartner.username?.charAt(0) }}
        </el-avatar>
        <span v-if="chatPartner">{{ chatPartner.nickname || chatPartner.username }}</span>
        <span v-else>加载中...</span>
      </div>
      <div class="negotiation-info" @click="showNegotiationDetail">
        <el-icon><InfoFilled /></el-icon> 协商详情
      </div>
    </div>
 
    <div class="messages-container" ref="messagesContainer">
      <div v-if="loading" class="loading-messages">
        <el-loading></el-loading>
      </div>
      <template v-else>
        <div v-if="messages.length > 0" class="date-divider">
          <span>{{ formatDate(messages[0]?.createdTime) }}</span>
        </div>
        <div v-for="(message, index) in messages" :key="message.messageId" 
             :class="['message', message.fromUserId === currentUserId ? 'sent' : 'received']">
          <!-- 如果当前消息日期与前一条消息日期不同，显示日期分隔符 -->
          <div v-if="index > 0 && !isSameDay(message.createdTime, messages[index-1].createdTime)" class="date-divider">
            <span>{{ formatDate(message.createdTime) }}</span>
          </div>
          <div class="message-wrapper">
            <!-- 头像 -->
            <div class="avatar-container">
              <el-avatar 
                :src="getUserAvatar(message)" 
                :size="40"
              >
                {{ getUserInitial(message) }}
              </el-avatar>
            </div>
            <div class="message-bubble">
              <!-- 发送者名称 -->
              <div class="sender-name">
                {{ getUserName(message) }}
              </div>
              <div class="message-time">{{ formatTime(message.createdTime) }}</div>
              
              <div class="message-content" v-if="message.messageType === 'TEXT'">
                {{ message.content }}
              </div>
              <div class="message-content" v-else-if="message.messageType === 'IMAGE'">
                <el-image 
                  :src="message.fileUrl" 
                  :preview-src-list="[message.fileUrl]"
                  fit="cover"
                  class="message-image"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                      <span>加载失败</span>
                    </div>
                  </template>
                </el-image>
              </div>
              
              <div v-if="message.status === 'RECALLED'" class="message-recalled">
                消息已撤回
              </div>
              <div class="message-status" v-if="message.fromUserId === currentUserId">
                {{ getMessageStatus(message.status) }}
                <el-button 
                  v-if="canRecallMessage(message)"
                  type="text" 
                  size="small"
                  @click="handleRecallMessage(message.messageId)"
                >
                  撤回
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>
    <div class="message-input">
      <div class="input-actions">
       <el-upload
  class="upload-item"
  action="#"
  :auto-upload="false"
  :show-file-list="false"
  :on-change="handleImageSelected"
  accept="image/*"
  :multiple="false"
>
  <el-tooltip content="发送图片" placement="top">
    <el-icon><Picture /></el-icon>
  </el-tooltip>
</el-upload>
      </div>
      <el-input
        v-model="newMessage"
        type="textarea"
        :rows="2"
        placeholder="输入消息..."
        @keyup.enter.exact.prevent="sendMessage"
        resize="none"
      ></el-input>
      <el-button type="primary" @click="sendMessage" :disabled="!newMessage.trim()">
        发送
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
import { 
  ArrowLeft, 
  InfoFilled, 
  Picture
} from '@element-plus/icons-vue';
import { getMessageHistory, sendMessage as sendMessageapi, markMessageAsRead, recallMessage } from '@/api/chat';
import { getNegotiationDetail } from '@/api/negotiation';
import { getUserById } from '@/api/user';
import { useUserStore } from '@/stores/user';

// 状态变量
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const negotiationId = ref(route.params.id);
const currentUserId = ref(null);
const userInfo = ref(null);
const negotiation = ref(null);
const messages = ref([]);
const newMessage = ref('');
const loading = ref(true);
const messagesContainer = ref(null);
const pollInterval = ref(null);
const notificationSound = new Audio('/notification.mp3');
const userCache = ref({}); // 缓存用户信息
const chatPartner = ref(null); // 聊天对象（广告主）

// 消息通知相关函数
const showMessageNotification = (message) => {
  notificationSound.play().catch(e => console.log('无法播放提示音:', e));

  ElNotification({
    title: chatPartner.value?.nickname + ' 发来新消息',
    message: message.messageType === 'TEXT' ? 
      message.content : 
      getMessageTypeText(message.messageType),
    type: 'success',
    position: 'top-right',
    duration: 3000,
    onClick: () => {
      scrollToBottom();
    }
  });
};

// 获取消息类型文本描述
const getMessageTypeText = (messageType) => {
  const typeMap = {
    'TEXT': '文本消息',
    'IMAGE': '[图片]'
  };
  return typeMap[messageType] || messageType;
};

// 开始轮询
const startPolling = () => {
  pollInterval.value = setInterval(async () => {
    await fetchMessages();
  }, 3000); // 每3秒轮询一次
};

// 初始化用户信息
const initUserInfo = async () => {
  try {
    if (!userStore.userInfo) {
      await userStore.getUserInfo();
    }
    userInfo.value = userStore.userInfo;
    currentUserId.value = userStore.userInfo.id;
    // 缓存当前用户信息（设备主）
    userCache.value[currentUserId.value] = userStore.userInfo;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessage.error('获取用户信息失败');
    router.push('/login');
  }
};

// 获取协商详情
const fetchNegotiationDetail = async () => {
  try {
    const res = await getNegotiationDetail(negotiationId.value);
    if (res.data.code === 200) {
      negotiation.value = res.data.data;
      // 获取聊天对象的详细信息（广告主）
      fetchChatPartnerInfo();
    } else {
      ElMessage.error(res.message || '获取协商详情失败');
    }
  } catch (error) {
    console.error('获取协商详情失败', error);
    ElMessage.error('获取协商详情失败');
  }
};

// 获取聊天对象信息（广告主）
const fetchChatPartnerInfo = async () => {
  if (!negotiation.value || !negotiation.value.advertiserUserId) return;
  
  try {
    const partnerId = negotiation.value.advertiserUserId;
    // 如果已经缓存过该用户的信息，直接使用
    if (userCache.value[partnerId]) {
      chatPartner.value = userCache.value[partnerId];
      return;
    }
    
    const res = await getUserById(partnerId);
    if (res.data.code === 200) {
      chatPartner.value = res.data.data;
      // 缓存用户信息
      userCache.value[partnerId] = res.data.data;
    }
  } catch (error) {
    console.error('获取聊天对象信息失败', error);
  }
};

// 获取用户信息
const fetchUserInfo = async (userId) => {
  // 如果已经缓存过该用户的信息，直接返回
  if (userCache.value[userId]) {
    return userCache.value[userId];
  }
  
  try {
    const res = await getUserById(userId);
    if (res.data.code === 200) {
      userCache.value[userId] = res.data.data;
      return res.data.data;
    }
  } catch (error) {
    console.error(`获取用户 ${userId} 信息失败`, error);
    return null;
  }
};

// 获取历史消息
const fetchMessages = async () => {
  try {
    if (!loading.value) {
      const res = await getMessageHistory(negotiationId.value);
      if (res.data.code === 200) {
        // 检查是否有新消息
        const newMessages = res.data.data.filter(
          msg => !messages.value.some(
            existingMsg => existingMsg.messageId === msg.messageId
          )
        );

        // 如果有新消息，显示通知
        for (const msg of newMessages) {
          if (msg.fromUserId !== currentUserId.value) {
            showMessageNotification(msg);
            markMessageAsRead(msg.messageId);
          }
          
          // 获取发送者信息
          if (!userCache.value[msg.fromUserId]) {
            await fetchUserInfo(msg.fromUserId);
          }
        }

        messages.value = res.data.data;
        nextTick(() => {
          scrollToBottom();
        });
      }
    } else {
      loading.value = true;
      const res = await getMessageHistory(negotiationId.value);
      if (res.data.code === 200) {
        messages.value = res.data.data;
        
        // 读取所有消息并标记为已读
        for (const msg of messages.value) {
          if (msg.status !== 'READ' && msg.fromUserId !== currentUserId.value) {
            markMessageAsRead(msg.messageId);
          }
          
          // 获取所有消息发送者的信息
          if (!userCache.value[msg.fromUserId]) {
            await fetchUserInfo(msg.fromUserId);
          }
        }
        
        loading.value = false;
        nextTick(() => {
          scrollToBottom();
        });
      } else {
        loading.value = false;
      }
    }
  } catch (error) {
    console.error('获取聊天记录失败', error);
    ElMessage.error('获取聊天记录失败');
    loading.value = false;
  }
};

// 获取用户头像
const getUserAvatar = (message) => {
  const user = userCache.value[message.fromUserId];
  return user?.avatar || '';
};

// 获取用户名称首字母（用于头像显示）
const getUserInitial = (message) => {
  const user = userCache.value[message.fromUserId];
  if (!user) return '';
  return (user.nickname || user.username || '')?.charAt(0)?.toUpperCase() || '';
};

// 获取用户名称
const getUserName = (message) => {
  const user = userCache.value[message.fromUserId];
  return user?.nickname || user?.username || `用户${message.fromUserId}`;
};

// 发送消息
const sendMessage = async () => {
  if (!newMessage.value.trim()) return;
  
  const messageDTO = {
    toUserId: negotiation.value.advertiserUserId,
    fromUserId: currentUserId.value,
    negotiationId: negotiationId.value,
    content: newMessage.value,
    messageType: 'TEXT'
  };
  
  try {
    const res = await sendMessageapi(messageDTO);
    if (res.data.code === 200) {
      messages.value.push(res.data);
      newMessage.value = '';
      scrollToBottom();
      await fetchMessages();
    } else {
      ElMessage.error(res.message || '发送消息失败');
    }
  } catch (error) {
    console.error('发送消息失败', error);
    ElMessage.error('发送消息失败');
  }
};

// 处理图片选择
// 1. 先从 common.js 导入通用上传接口
import { upload } from '@/api/common';

// 2. 修改 handleImageSelected 函数
const handleImageSelected = async (uploadFile) => {
  if (!uploadFile || !uploadFile.raw) {
    console.error('未获取到文件或文件为空', uploadFile);
    ElMessage.error('未获取到文件或文件为空');
    return;
  }
  
  const file = uploadFile.raw;
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('请选择图片文件');
    return;
  }
  
  try {
    // 显示上传中提示
    const loadingMessage = ElMessage({
      message: '正在上传图片...',
      type: 'info',
      duration: 0
    });
    
    // 1. 先上传图片获取URL
    const formData = new FormData();
    formData.append('file', file);
    formData.append('path', 'chat/images'); // 指定存储路径
    
    const uploadRes = await upload(formData);
    
    if (uploadRes.data && uploadRes.data.code === 200) {
      const fileUrl = uploadRes.data.data;
      
      // 2. 然后发送带有图片URL的消息
      const messageDTO = {
        toUserId: negotiation.value.advertiserUserId,
        fromUserId: currentUserId.value,
        negotiationId: negotiationId.value,
        content: fileUrl, // 使用URL作为消息内容
        messageType: 'IMAGE',
        fileUrl: fileUrl,
        fileName: file.name,
        fileSize: file.size
      };
      
      console.log('发送的消息内容:', messageDTO);
      const res = await sendMessageapi(messageDTO);
      
      // 关闭加载提示
      loadingMessage.close();
      
      if (res.data && res.data.code === 200) {
        ElMessage.success('图片发送成功');
        await fetchMessages();
      } else {
        console.error('发送图片消息失败:', res);
        ElMessage.error(res.data?.message || '发送图片消息失败');
      }
    } else {
      // 关闭加载提示
      loadingMessage.close();
      console.error('图片上传失败:', uploadRes);
      ElMessage.error(uploadRes.data?.message || '图片上传失败');
    }
  } catch (error) {
    console.error('发送图片失败:', error);
    ElMessage.error('发送图片失败: ' + (error.message || '未知错误'));
  }
};

// 判断消息是否可以撤回（2分钟内）
const canRecallMessage = (message) => {
  if (message.fromUserId !== currentUserId.value || message.status === 'RECALLED') {
    return false;
  }
  const now = new Date();
  const messageTime = new Date(message.createdTime);
  return (now - messageTime) <= 2 * 60 * 1000;
};

// 撤回消息
const handleRecallMessage = async (messageId) => {
  try {
    await ElMessageBox.confirm('确定要撤回这条消息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const res = await recallMessage(messageId, currentUserId.value);
    if (res.data.code === 200) {
      const index = messages.value.findIndex(msg => msg.messageId === messageId);
      if (index !== -1) {
        messages.value[index].status = 'RECALLED';
      }
    } else {
      ElMessage.error(res.message || '撤回消息失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('撤回消息失败', error);
      ElMessage.error('撤回消息失败');
    }
  }
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  const today = new Date();
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1);
  
  if (date.toDateString() === today.toDateString()) {
    return '今天';
  } else if (date.toDateString() === yesterday.toDateString()) {
    return '昨天';
  } else {
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
  }
};
// 判断两个时间是否是同一天
const isSameDay = (timestamp1, timestamp2) => {
  if (!timestamp1 || !timestamp2) return false;
  const date1 = new Date(timestamp1);
  const date2 = new Date(timestamp2);
  return date1.toDateString() === date2.toDateString();
};

// 获取消息状态中文描述
const getMessageStatus = (status) => {
  const statusMap = {
    'SENT': '已发送',
    'DELIVERED': '已送达',
    'READ': '已读',
    'RECALLED': '已撤回'
  };
  return statusMap[status] || status;
};
// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
      
      // 添加延时再次滚动以确保在某些情况下能正确滚动
      setTimeout(() => {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
      }, 100);
    }
  });
};
// 返回上一页
const goBack = () => {
  router.back();
};
// 查看协商详情
const showNegotiationDetail = () => {
  router.push({
    path: `/device-owner/negotiation/${negotiationId.value}`
  });
};
onMounted(async () => {
  await initUserInfo();
  await fetchNegotiationDetail();
  await fetchMessages();
  // 启动轮询，实现实时消息更新
  startPolling();
  // 添加一个额外的延时滚动，处理可能的图片加载延迟
  setTimeout(() => {
    scrollToBottom();
  }, 300);
});
onUnmounted(() => {
  // 清除轮询计时器，避免内存泄漏
  if (pollInterval.value) {
    clearInterval(pollInterval.value);
  }
});
</script>
<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 140px); /* 减去头部导航和内容区padding的高度 */
  background-color: #f8f9fa;
  font-family: 'Helvetica Neue', Arial, sans-serif;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin: -20px; /* 抵消内容区的padding */
  position: relative;
}

.chat-header {
  position: relative;
  z-index: 10;
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  padding: 16px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 1px solid #eaeaea;
  border-radius: 8px 8px 0 0;
}

.chat-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  display: flex;
  align-items: center;
  gap: 10px;
}

.title-avatar {
  border: 2px solid rgba(255, 152, 0, 0.2);
}

.back-button, .negotiation-info {
  cursor: pointer;
  color: #3880ff;
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.back-button:hover, .negotiation-info:hover {
  color: #2a6de9;
}

.messages-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  
  background-color: #f8f9fa;
  background-image: linear-gradient(rgba(255, 255, 255, 0.7) 1px, transparent 1px),
                    linear-gradient(90deg, rgba(255, 255, 255, 0.7) 1px, transparent 1px);
  background-size: 20px 20px;
  position: relative;
  height: calc(100% - 120px); /* 减去输入框的高度 */
}

.date-divider {
  text-align: center;
  margin: 20px 0;
  position: relative;
  clear: both;
}

.date-divider span {
  background-color: #e4e9f2;
  color: #606266;
  padding: 3px 10px;
  border-radius: 10px;
  font-size: 12px;
  display: inline-block;
}

.message {
  margin-bottom: 24px;
  clear: both;
  animation: fadeIn 0.3s ease;
  max-width: 75%;
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.sent .message-wrapper {
  flex-direction: row-reverse;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.sent {
  float: right;
}

.received {
  float: left;
}

.avatar-container {
  flex-shrink: 0;
  position: relative;
}

.sent .avatar-container::after {
  content: '';
  position: absolute;
  width: 10px;
  height: 10px;
  background-color: #2196F3;  /* 设备主使用蓝色 */
  border-radius: 50%;
  bottom: 0;
  right: 0;
  border: 2px solid white;
}

.received .avatar-container::after {
  content: '';
  position: absolute;
  width: 10px;
  height: 10px;
  background-color: #ff9800;  /* 广告主使用橙色 */
  border-radius: 50%;
  bottom: 0;
  right: 0;
  border: 2px solid white;
}

.message-bubble {
  display: flex;
  flex-direction: column;
  max-width: calc(100% - 50px);
}

.sender-name {
  font-size: 12px;
  color: #666;
  margin-bottom: 3px;
  font-weight: 500;
}

.sent .sender-name {
  text-align: right;
  color: #2196F3;  /* 设备主名称使用蓝色 */
}

.received .sender-name {
  text-align: left;
  color: #ff9800;  /* 广告主名称使用橙色 */
}

.message-content {
  padding: 12px 16px;
  border-radius: 18px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  word-break: break-word;
  line-height: 1.5;
  position: relative;
}

.sent .message-content {
  background-color: #e3f2fd;  /* 设备主气泡使用浅蓝色 */
  border-bottom-right-radius: 4px;
  color: #2c2c2c;
  margin-left: auto;
}

.received .message-content {
  background-color: #fff;
  border-bottom-left-radius: 4px;
  color: #2c2c2c;
}

.message-time {
  font-size: 11px;
  color: #888;
  margin-bottom: 4px;
  opacity: 0.8;
  align-self: flex-start;
}

.sent .message-time {
  margin-left: auto;
}

.message-status {
  font-size: 11px;
  color: #888;
  text-align: right;
  margin-top: 4px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 8px;
}

.message-recalled {
  font-style: italic;
  color: #888;
  text-align: center;
  padding: 5px;
  background-color: rgba(0, 0, 0, 0.05);
  border-radius: 10px;
  margin: 5px 0;
}

.file-message {
  display: flex;
  align-items: center;
  gap: 10px;
  background-color: #fff;
  border-radius: 10px;
  padding: 12px;
  min-width: 200px;
}

.sent .file-message {
  background-color: #e3f2fd;
}

.file-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #2c2c2c;
  font-weight: 500;
}

.file-size {
  font-size: 11px;
  color: #888;
  margin-left: 5px;
}

.message-image {
  max-width: 220px;
  max-height: 220px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.message-image:hover {
  transform: scale(1.02);
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background-color: #f1f1f1;
  border-radius: 10px;
  color: #888;
}

.negotiate-message {
  background-color: #fff;
  border: 1px solid #eaeaea;
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  min-width: 220px;
}

.sent .negotiate-message {
  background-color: #e3f2fd;
}

.negotiate-title {
  font-weight: 600;
  margin-bottom: 12px;
  color: #333;
  font-size: 16px;
  border-bottom: 1px solid #eaeaea;
  padding-bottom: 8px;
}

.negotiate-price {
  color: #ff6600;
  font-size: 22px;
  margin-bottom: 12px;
  font-weight: 600;
}

.negotiate-slots {
  margin-bottom: 12px;
  font-size: 14px;
  color: #555;
  background: #f9f9f9;
  border-radius: 8px;
  padding: 8px 12px;
}

.negotiate-remark {
  color: #666;
  font-size: 14px;
  border-top: 1px solid #eee;
  padding-top: 12px;
  margin-top: 12px;
  font-style: italic;
}

.message-input {
  position: fixed; 
  bottom: 15px; 
  left: 230px; 
  right: 10px; 
  background-color: #fff;
  padding: 15px 20px;
  display: flex;
  align-items: flex-end;
  gap: 12px;
  border: 1px solid #eaeaea;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  z-index: 100;
  transition: left 0.3s ease;
}

/* 添加一个媒体查询，处理侧边栏折叠时的情况 */
@media screen and (max-width: 768px) {
  .message-input {
    left: 84px; /* 侧边栏折叠时的宽度 + 20px padding */
  }
}

/* 确保输入框在侧边栏折叠时也能正确定位 */
.main-content.expanded .message-input {
  left: 84px; /* 侧边栏折叠时的宽度 + 20px padding */
}

.input-actions {
  display: flex;
  gap: 16px;
}

.upload-item {
  cursor: pointer;
  color: #666;
  font-size: 22px;
  transition: all 0.2s ease;
}

.upload-item:hover {
  color: #2196F3; /* 与设备主身份匹配的颜色 */
  transform: scale(1.1);
}

.el-textarea :deep(.el-textarea__inner) {
  border-radius: 20px;
  padding: 10px 15px;
  resize: none;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.02);
  max-height: 80px;
}

.el-textarea :deep(.el-textarea__inner:focus) {
  border-color: #2196F3; /* 与设备主身份匹配的颜色 */
  box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.2);
}

.el-button {
  border-radius: 20px;
  padding: 10px 24px;
  font-weight: 500;
}

.loading-messages {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 30px;
}

/* 自定义滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: transparent;
}

.messages-container::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 4px;
}

/* 聊天气泡箭头样式 */
.received .message-content::before {
  content: '';
  position: absolute;
  left: -8px;
  top: 15px;
  border-style: solid;
  border-width: 8px 8px 8px 0;
  border-color: transparent #fff transparent transparent;
}

.sent .message-content::after {
  content: '';
  position: absolute;
  right: -8px;
  top: 15px;
  border-style: solid;
  border-width: 8px 0 8px 8px;
  border-color: transparent transparent transparent #e3f2fd; /* 匹配设备主气泡颜色 */
}

/* 头像样式增强 */
:deep(.el-avatar) {
  border: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  background-color: #fff;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .message {
    max-width: 85%;
  }
  
  .message-image {
    max-width: 180px;
  }
  
  .chat-header {
    padding: 12px 16px;
  }
  
  .negotiate-message {
    padding: 12px;
  }
  
  .negotiate-title {
    font-size: 14px;
  }
  
  .negotiate-price {
    font-size: 18px;
  }
}

/* 添加一些交互效果 */
.message-wrapper {
  transition: transform 0.2s ease;
}

.message-wrapper:hover {
  transform: translateY(-2px);
}

.avatar-container {
  transition: all 0.2s ease;
}

.avatar-container:hover {
  transform: scale(1.05);
}

/* 隐藏其他区域的滚动条 */
::-webkit-scrollbar {
  width: 0;
  display: none;
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .chat-container {
    background-color: #1e1e1e;
  }
  
  .chat-header {
    background-color: #2d2d2d;
    border-color: #3d3d3d;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  }
  
  .chat-title {
    color: #e0e0e0;
  }
  
  .back-button, .negotiation-info {
    color: #4d90fe;
  }
  
  .back-button:hover, .negotiation-info:hover {
    color: #6ca0fc;
  }
  
  .messages-container {
    background-color: #1e1e1e;
    background-image: linear-gradient(rgba(255, 255, 255, 0.1) 1px, transparent 1px),
                      linear-gradient(90deg, rgba(255, 255, 255, 0.1) 1px, transparent 1px);
  }
  
  .date-divider span {
    background-color: #3d3d3d;
    color: #c0c0c0;
  }
  
  .sent .message-content {
    background-color: #0d3a63;
    color: #e0e0e0;
  }
  
  .received .message-content {
    background-color: #2d2d2d;
    color: #e0e0e0;
  }
  
  .message-time {
    color: #a0a0a0;
  }
  
  .message-status {
    color: #a0a0a0;
  }
  
  .message-recalled {
    color: #a0a0a0;
    background-color: rgba(255, 255, 255, 0.1);
  }
  
  .file-message {
    background-color: #2d2d2d;
  }
  
  .sent .file-message {
    background-color: #0d3a63;
  }
  
  .file-name {
    color: #e0e0e0;
  }
  
  .file-size {
    color: #a0a0a0;
  }
  
  .image-error {
    background-color: #3d3d3d;
    color: #a0a0a0;
  }
  
  .message-input {
    background-color: #2d2d2d;
    border-color: #3d3d3d;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  }
  
  .el-textarea :deep(.el-textarea__inner) {
    background-color: #3d3d3d;
    border-color: #4d4d4d;
    color: #e0e0e0;
  }
  
  .el-textarea :deep(.el-textarea__inner:focus) {
    border-color: #2196F3;
    box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.2);
  }
  
  .sent .message-content::after {
    border-color: transparent transparent transparent #0d3a63;
  }
  
  .received .message-content::before {
    border-color: transparent #2d2d2d transparent transparent;
  }
}
</style>